/**
 * Copyright (c) [2021] [tenny]
   [fastify-pithy-session] is licensed under Mulan PSL v2.
   You can use this software according to the terms and conditions of the Mulan PSL v2. 
   You may obtain a copy of Mulan PSL v2 at:
            http://license.coscl.org.cn/MulanPSL2 
   THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.  
   See the Mulan PSL v2 for more details. 
 */
const crypto = require('crypto');

/**
 * 将 JSON 对象转换为 base64 格式
 * @param {*} body
 * @returns string  base64 格式的字符串
 * @api private
 */
function encode(body) {
  return Buffer.from(JSON.stringify(body)).toString('base64');
}

/**
 * 将 JSON 对象的 base64字符串转换为 JSON 对象
 * @param {string} string base64格式的字符串
 * @return JSON 对象
 * @api private
 */
function decode(string) {
  const body = Buffer.from(string, 'base64').toString('utf8');
  return JSON.parse(body);
}

/**
 * 构建一个session内容摘要
 * @param {Object} json 待计算摘要的session json
 * @returns md5-hash
 */
function hash(json) {
  return crypto.createHash('md5').update(JSON.stringify(json)).digest('hex');
}

/**
 * 解析 session
 * @param {JSONObject} json session 的 json 值
 */
function parseSession(json) {
  let value = {};
  let expire = {};
  let expireLen = 0;
  for (let key in json) {
    if (key === 'symbol__maxAge') {
      expire.maxAge = json[key];
      expireLen++;
    } else if (key === 'symbol__expire') {
      expire.expire = json[key];
      expireLen++;
    } else {
      value[key] = json[key];
    }
  }
  return { value, expire: expireLen > 0 ? expire : null };
}

module.exports = {
  encode,
  decode,
  hash,
  parseSession,
};
